<script setup>
import { ref, onMounted, toRaw, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {Plus, Edit, Delete, Search, Histogram} from '@element-plus/icons-vue'

//引入API
// import {} from '../../api/attendance.js'
// import {} from '../../api/emp.js'

const tableLoading = ref(true);
// 数据
const currentPageNum = ref(1);//当前页码
const currentPageSize = ref(5);//每页显示的最大数据量
const dataArr = ref([]);//当前页数据
const total = ref(0);//总数据量

function doLoadTableDatas() {//加载表格数据
    tableLoading.value = true;//开始加载
    //TODO: 使用API根据条件加载数据
    //主要查询条件
    let params = {
        pageNum: currentPageNum.value,
        pageSize: currentPageSize.value,
        no: searchFormData.value.no,
        name: searchFormData.value.name,
        month: searchFormData.value.month,
    };
    console.log('search params:', params);

    //模拟数据加载操作
    const loadData = () => {
        return {
            total: 100,
            data: [
                {id:1,empId:1,no:'000001',name:'汤姆1',day:'2024-08-05',startTime:'2024-08-05 08:30:34',startRemark:'无1',endTime:'2024-08-05 17:31:16',endRemark:'无无22',recordDate:'2024-08-05 08:30:34'},
                {id:2,empId:2,no:'000002',name:'汤姆2',day:'2024-08-05',startTime:'2024-08-05 08:30:34',startRemark:'上班了',endTime:'2024-08-05 17:31:16',endRemark:'下班了',recordDate:'2024-08-05 08:30:34'},
                {id:3,empId:3,no:'000003',name:'汤姆3',day:'2024-08-05',startTime:'2024-08-05 08:30:34',startRemark:'',endTime:'2024-08-05 17:31:16',endRemark:'',recordDate:'2024-08-05 08:30:34'},
                {id:4,empId:4,no:'000004',name:'汤姆4',day:'2024-08-05',startTime:'2024-08-05 08:30:34',startRemark:'',endTime:'2024-08-05 17:31:16',endRemark:'',recordDate:'2024-08-05 08:30:34'},
                {id:5,empId:5,no:'000005',name:'汤姆5',day:'2024-08-05',startTime:'2024-08-05 08:30:34',startRemark:'',endTime:'2024-08-05 17:31:16',endRemark:'',recordDate:'2024-08-05 08:30:34'},
            ]
        }
    };
    const result = loadData();

    //成功后执行以下操作
    //处理响应数据
    dataArr.value = result.data;
    total.value = result.total;
    tableLoading.value = false;//加载完成

}

onMounted(()=> {//挂载后执行
    doLoadTableDatas();//核心表格数据
    
});

const tableSelectObj = ref(null);//选中行对象
function doTableSelectionChange(selected) {//选中操作
    //选中变化
    console.log('doTableSelectionChange:', selected);
    tableSelectObj.value = selected;
}

function doShowAdd(type) {
    addFormHeight.value = addFormHeight.value == 0 ? 200:0;
}
function doModify() {
    if(tableSelectObj.value == null) {
        ElMessage.warning('请选择需要修改的行');
        return;
    }
    //设置数据
    const obj = toRaw(tableSelectObj.value);//取原对象
    const newValue = structuredClone(obj);//克隆
    formData.value = newValue;
    formData.value.clockType = 1;//打卡类型: 1上班,2下班
    formData.value.remark = newValue.startRemark;//上/下班备注
    formData.value.timeModifyType = 1;//1不更新时间,2更新时间

    //成功后打开对话框
    dialogFlag.value = true;
}
function doRemove() {
    if(tableSelectObj.value == null) {
        ElMessage.warning('请选择需要删除的行');
        return;
    }
    //TODO: 执行数据删除

    //成功后执行以下操作
    ElMessage.success('删除成功');
    //重新加载数据
    doLoadTableDatas();
}

//搜索
const searchFormData = ref({no:'', name:'', month:''});
let nowDay = new Date();
searchFormData.value.month = nowDay.getFullYear() + '-' + ((nowDay.getMonth()+1)+'').padStart(2,'0');

const searchFormRef = ref(null);
function doFormSearch() {
    if(tableLoading.value) {
        ElMessage.warning('正在查询中...');
        return;
    }
    //console.log('searchFormData:', toRaw(searchFormData.value));
    let oldPageNum = currentPageNum.value;
    currentPageNum.value = 1;//从头开始查询
    if(oldPageNum == 1) {//防止重复加载
        // 根据条件加载数据
        doLoadTableDatas();
    }
}

//分页变化,加载数据
watch(currentPageNum, (nv, ov, onCleanup)=>{
    doLoadTableDatas();
});
watch(currentPageSize, (nv, ov, onCleanup)=>{
    doLoadTableDatas();
});

//统计
const sdLoading = ref(false);
const statisticsDataArr = ref([]);
const totalDay = ref(22);//总上班天数
function doStatistics() {
    sdLoading.value = true;
    //TODO: 获取统计数据
    setTimeout(()=>{
        let data = [
            // 总打卡天数, 正常上班打卡次数,迟到上班打卡次数,上班缺卡次数, 正常下班打卡次数,早退下班打卡次数,下班缺卡次数
            {no:'000001',name:'汤姆1',total:22,startOk:22,startNo:0,startNone:0,endOk:22,endNo:0,endNone:0},
            {no:'000002',name:'汤姆2',total:22,startOk:20,startNo:2,startNone:0,endOk:22,endNo:0,endNone:0},
            {no:'000003',name:'汤姆3',total:22,startOk:21,startNo:1,startNone:0,endOk:20,endNo:0,endNone:2},
            {no:'000004',name:'汤姆4',total:22,startOk:22,startNo:0,startNone:0,endOk:22,endNo:0,endNone:0},
            {no:'000005',name:'汤姆5',total:22,startOk:18,startNo:3,startNone:1,endOk:20,endNo:1,endNone:1},
        ];

        //成功后执行以下操作
        statisticsDataArr.value = data;
        sdLoading.value = false;
    }, 500);
}

//更新打卡
//对话框中表单数据, time 1上班 2下班
const formData = ref({id:undefined,empId:1,no:'000001',name:'汤姆1',time:1,day:'2024-08-05',startTime:'2024-08-05 08:30:34',startRemark:'',endTime:'2024-08-05 17:31:16',endRemark:'',recordDate:'2024-08-05 08:30:34'});
const formRef = ref(null);
const dialogFlag = ref(false);
function doDialogBeforeClose(done) {
    //关闭操作
    done();
    formRef.value.clearValidate();//清除校验标记
}
function doCloseDialog(type) {
    if(type === 0) {
        //取消操作
        dialogFlag.value = false;
        formRef.value.clearValidate();//清除校验标记
        return;
    }
    if(type === 1) {
        //确定操作
        //TODO: 提交修改的数据
        console.log('formData.value:', formData.value);
        let data = {id:formData.value.id, clockType:formData.value.clockType, remark:formData.value.remark, timeModifyType: formData.value.timeModifyType};
        console.log('update data:', data);

        //成功后执行以下操作
        dialogFlag.value = false;
        ElMessage.success('修改成功');
        //重新加载数据
        doLoadTableDatas();
    }
}
function doFormDataRadioChange(val) {
    if(val == 1) {
        formData.value.remark = formData.value.startRemark;
        return;
    }
    formData.value.remark = formData.value.endRemark;
}

//打卡
const addFormHeight = ref(0);
const addFormData = ref({clockType: 1, remark: ''});
const addFormRef = ref(null);
function doAddFormSubmit() {
    addFormRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('校验通过');
            //TODO: 提交添加的数据
            let params = toRaw(addFormData.value);
            console.log('addFormData:', params);

            //成功后执行以下操作
            ElMessage.success('打卡成功');
            //重新加载数据
            doLoadTableDatas();
        } else { 
            //console.log('校验不通过:', fields);
            ElMessage.warning('信息有误，请查看对应的提示信息');
        }
    });;
}
function doAddFormReset() {//表单重置
    addFormRef.value.resetFields();
}
function doAddFormClose() {
    addFormHeight.value = 0;//隐藏表单
    addFormRef.value.resetFields();//重置表单
}

</script>
<template>
    <div>
        <div class="title-dl">考勤记录列表</div>
        <div class="tool-btns" >
            <!-- search表单 -->
            <el-form :model="searchFormData" :inline="true" ref="searchFormRef" >
                <el-form-item label="员工工号：" prop="no">
                    <el-input v-model="searchFormData.no" autocomplete="off" placeholder="请输入员工工号" clearable style="width: 160px" />
                </el-form-item>
                <el-form-item label="姓名：" prop="name">
                    <el-input v-model="searchFormData.name" autocomplete="off" placeholder="请输入员工姓名" clearable style="width: 160px" />
                </el-form-item>
                <el-form-item label="月份：" prop="month">
                    <el-date-picker type="month" v-model="searchFormData.month" placeholder="选择月份" format="YYYY-MM" value-format="YYYY-MM" style="width: 160px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="doFormSearch">查询</el-button>
                    <el-button type="success" :icon="Histogram" @click="doStatistics">统计</el-button>
                </el-form-item>
            </el-form>

            <el-button type="success" :icon="Plus" @click="doShowAdd">打卡</el-button>
            <el-button type="warning" :icon="Edit" @click="doModify">更新打卡</el-button>
            <el-button type="danger" :icon="Delete" @click="doRemove">删除</el-button>

            <div class="add-form-dl" :style="{height: addFormHeight+'px'}" >
                <div class="title-dl">打卡</div>
                <!-- 新增一条考核记录 -->
                <el-form :model="addFormData" label-width="130px" ref="addFormRef">
                    <el-form-item label="时间：" prop="clockType">
                        <el-radio-group v-model="addFormData.clockType" >
                            <el-radio-button label="上班" :value="1" />
                            <el-radio-button label="下班" :value="2" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="备注：" prop="remark">
                        <el-input type="textarea" v-model="addFormData.remark" autocomplete="off" autosize />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="doAddFormSubmit">确定</el-button>
                        <el-button @click="doAddFormReset" >重置</el-button>
                        <el-button type="info" @click="doAddFormClose" >关闭</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="content-dl" v-loading="tableLoading" >
            <!-- 根据情况增减列 -->
            <el-table :data="dataArr" stripe border @current-change="doTableSelectionChange" highlight-current-row>
                <el-table-column prop="no" label="员工工号" width="120" show-overflow-tooltip  />
                <el-table-column prop="name" label="姓名" show-overflow-tooltip />
                <el-table-column prop="day" label="日期" width="120" show-overflow-tooltip />
                <el-table-column prop="startTime" label="上班打卡" width="180" show-overflow-tooltip />
                <el-table-column prop="startRemark" label="上班打卡备注" width="120" show-overflow-tooltip />
                <el-table-column prop="endTime" label="下班打卡" width="180" show-overflow-tooltip />
                <el-table-column prop="endRemark" label="上班打卡备注" width="120" show-overflow-tooltip />
                <el-table-column prop="recordDate" label="记录时间" width="200" show-overflow-tooltip />
            </el-table>
            <el-pagination class="page-dl" layout="total, jumper, prev, pager, next" :total="total"
            v-model:current-page="currentPageNum" v-model:page-size="currentPageSize"
            :pager-count="5" hide-on-single-page size="large" />
        </div>

        <el-dialog v-model="dialogFlag" :title="'更新 ['+(formData.clockType==1?'上班':'下班')+'] 打卡'" width="500" 
        :before-close="doDialogBeforeClose" center align-center draggable
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        >
            <el-form :model="formData" label-width="130px" ref="formRef">
                <el-form-item label="员工工号：" prop="no">
                    <el-input v-model="formData.no" autocomplete="off" readonly />
                </el-form-item>
                <el-form-item label="姓名：" prop="name">
                    <el-input v-model="formData.name" autocomplete="off" readonly />
                </el-form-item>
                <el-form-item label="时间：" prop="clockType">
                    <el-radio-group v-model="formData.clockType" @change="doFormDataRadioChange">
                        <el-radio-button label="上班" :value="1" />
                        <el-radio-button label="下班" :value="2" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="更新打卡时间：" prop="timeModifyType">
                    <el-radio-group v-model="formData.timeModifyType">
                        <el-radio label="不更新" :value="1" />
                        <el-radio label="更新" :value="2" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注：" prop="remark">
                    <el-input type="textarea" v-model="formData.remark" autocomplete="off" autosize />
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="doCloseDialog(0)">取消</el-button>
                    <el-button type="primary" @click="doCloseDialog(1)">确定</el-button>
                </div>
            </template>
        </el-dialog>
        
        <hr>
        <div class="statistics-dl" >
            <div class="title-dl">{{searchFormData.month}}月 统计结果</div>
            <el-table :data="statisticsDataArr" stripe border v-loading="sdLoading" >
                <el-table-column prop="no" label="员工工号" width="120" show-overflow-tooltip  />
                <el-table-column prop="name" label="姓名" show-overflow-tooltip />
                <el-table-column prop="total" label="实际总打卡天数" width="130" show-overflow-tooltip />
                <el-table-column prop="startOk" label="正常上班打卡次数" width="140" show-overflow-tooltip >
                    <template #default="scope">
                        <span style="color: #67c23a;" >{{ scope.row.startOk }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="startNo" label="迟到次数" width="90" show-overflow-tooltip >
                    <template #default="scope">
                        <span style="color: #f56c6c;" >{{ scope.row.startNo }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="startNone" label="上班缺卡次数" width="110" show-overflow-tooltip >
                    <template #default="scope">
                        <span style="color: #e6a23c;" >{{ scope.row.startNone }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="endOk" label="正常下班打卡次数" width="140" show-overflow-tooltip >
                    <template #default="scope">
                        <span style="color: #67c23a;" >{{ scope.row.endOk }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="endNo" label="早退次数" width="90" show-overflow-tooltip >
                    <template #default="scope">
                        <span style="color: #f56c6c;" >{{ scope.row.endNo }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="endNone" label="下班缺卡次数" width="110" show-overflow-tooltip >
                    <template #default="scope">
                        <span style="color: #e6a23c;" >{{ scope.row.endNone }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>
<style scoped>
.title-dl {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 10px;
}
.tool-btns {
    margin-bottom: 10px;
}
.add-form-dl {
    margin-top: 10px;
    width: 600px;
    overflow-y: auto;
    transition: height 0.5s linear;
}
.page-dl {
    margin-top: 10px;
}
.statistics-dl {
    margin: 10px 0;
}
</style>